<template>
    <div class="information-list py-4">
        <div class="information-content">
            <div class="flex flex-col lg:flex-row gap-4">
                <!-- 左侧主要内容区域 -->
                <div class="flex-1">
                    <!-- 轮播图广告位 -->
                    <div class="mb-4" v-if="newsTopList.length > 0">
                        <div class="relative rounded-lg overflow-hidden shadow-md">
                            <div class="carousel-container">
                                <el-carousel height="300px" :autoplay="true">
                                    <el-carousel-item v-for="item in newsTopList" :key="item">
                                        <div class="carousel-img-box" @click="goDetails(item.id)">
                                            <img :src="item.coverImageUrl" :alt="item.coverImageUrl"
                                                class="w-full object-fill information-img">
                                            <div class="filter-img-box">
                                                <div class="filter-bg"></div>
                                                <img class="filter-img" :src="item.coverImageUrl">
                                                <div
                                                    class="filter-text top-0 left-0 right-0 p-4 text-white flex flex-col">
                                                    <div class="text-xl font-semibold mb-1">{{ item.title }}</div>
                                                    <div class="text-sm opacity-90 mt-2 w-4/5 line-clamp-4">{{
                                                        item.contentSummary }}</div>
                                                    <div class="mt-2 flex justify-between items-center text-sm mt-auto">
                                                        <span class="flex items-center">
                                                            <el-icon class="mr-1">
                                                                <Clock />
                                                            </el-icon>
                                                            <DateConvert :date="item.publishTime"></DateConvert>
                                                        </span>
                                                        <span class="flex items-center">
                                                            <el-icon class="mr-1">
                                                                <View />
                                                            </el-icon>
                                                            <span>{{ item.viewCount }}</span>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </el-carousel-item>
                                </el-carousel>
                            </div>
                        </div>
                    </div>

                    <!-- 分类标签 -->
                    <div class="mb-4">
                        <div class="flex flex-wrap gap-2">
                            <button :class="[
                                'px-4 py-2 rounded-full text-sm',
                                queryParams.category === ''
                                    ? 'bg-blue-600 text-white'
                                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            ]" @click="changeCategory('')">
                                全部
                            </button>
                            <button v-for="category in news_category" :key="category.dictValue" :class="[
                                'px-4 py-2 rounded-full text-sm',
                                queryParams.category === category.dictValue
                                    ? 'bg-blue-600 text-white'
                                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            ]" @click="changeCategory(category.dictValue)">
                                {{ category.dictLabel }}
                            </button>
                        </div>
                    </div>
                    <!-- 列表顶部广告位 -->
                    <div class="grid grid-cols-1 gap-6 mb-4 content-top-a"
                    @click="goAd(contentTopAd)"
                    v-if="contentTopAd.adImageUrl">
                        <img :src="contentTopAd.adImageUrl" :alt="contentTopAd.adDescription"
                            style="width: 100%;height: 80px;">
                        <div class="right-a-tag" v-if="contentTopAd.showAdTag">广告</div>
                    </div>
                    <!-- 资讯列表 -->
                    <div class="grid grid-cols-1 gap-4">
                        <div v-for="item in newsList" :key="item.id" @click="goDetails(item.id)"
                            class="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow duration-300">
                            <div class="flex flex-col md:flex-row">
                                <div class="" style="width: 320px;height: 160px;">
                                    <div class="aspect-w-16 aspect-h-9"
                                        style="width: 300px;height: 160px; padding: 10px;">
                                        <img :src="item.coverImageUrl" :alt="item.title"
                                            style="border-radius: 10px;border:none" class="w-full h-full object-fill">
                                    </div>
                                </div>
                                <div class="p-2 news-item-text " style="flex: 1;">
                                    <h3 class="text-lg font-semibold text-gray-800 mb-2">
                                        {{ item.title }}
                                    </h3>
                                    <p class="text-gray-600 text-sm mb-4 description-box">
                                        {{ item.contentSummary }}
                                    </p>
                                    <div class="bottom-box flex justify-between items-center text-sm text-gray-500">
                                        <div class="flex items-center">
                                            <img :src="item.creatorAvatar"
                                                style="width: 20px;height: 20px;border-radius: 50%;" alt="">
                                            <span>{{ item.creatorName }} </span>
                                            <span>
                                                <el-tag style="margin-left: 5px;" v-for="tag in item.tagsBtn" :key="tag"
                                                    type="info">{{ tag }}</el-tag>
                                            </span>
                                        </div>
                                        <div>
                                            <span><date-convert :date="item.publishTime"
                                                    format="YYYY-MM-DD HH:mm:ss"></date-convert></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 分页 -->
                    <div class="mt-4 flex justify-between mb-2">
                        <div class="total">共{{ total }}项数据</div>
                        <el-pagination style="justify-content: center" background layout="prev, pager, next"
                            :total="total" v-model:current-page="queryParams.pageNum"
                            v-model:page-size="queryParams.pageSize" @size-change="getNewsListFun"
                            @current-change="getNewsListFun" />
                    </div>
                    <!-- 底部广告 -->
                    <div class="mb-4 gap-4 footer-carousel-box">
                        <div class="footer-carousel-container" ref="footerCarouselContainer">
                            <div class="footer-carousel-wrapper" ref="footerCarouselWrapper">
                                <div class="footer-carousel"
                                @click="goAd(item)"
                                v-for="(item, index) in displayAds" :key="index">
                                    <img :src="item.adImageUrl" :alt="item.adDescription" class="w-full aspect-video object-fill">
                                    <div class="right-a-tag" v-if="item.showAdTag">广告</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧广告区域 -->
                <div style="width: 330px;" class=" space-y-4">


                    <!-- 右侧广告位 -->
                    <div class="bg-white rounded-lg shadow-md sidebar-a-box"
                    @click="goAd(item)"
                    v-for="item in sidebarAd" :key="item.id">
                        <div class="bg-gray-100 rounded-lg overflow-hidden">
                            <img :src="item.adImageUrl" :alt="item.adDescription" class="w-full aspect-video object-cover">
                        </div>
                        <div class="right-a-tag" v-if="item.showAdTag">广告</div>
                    </div>
                    <!-- 我的关注 -->
                    <div class="bg-white rounded-lg shadow-md p-4 py-2">
                        <h3 class="text-lg font-semibold text-gray-800 mb-2 flex justify-between items-center gap-2">
                            <HeartIcon size="16" color="#007bff"></HeartIcon>
                            <span>我的关注</span>
                            <span class="ml-auto text-sm text-gray-600 hover:text-blue-600 cursor-pointer" @click="goFollowList"></span>
                        </h3>
                        <div class="text-center py-8"  v-if="!token">
                            <button class="text-blue-600 hover:text-blue-700" @click="login">登录后查看</button>
                        </div>
                        <div class="text-center py-2" v-else>
                            <div class="grid grid-cols-3 gap-4" v-if="followList.length > 0">
                                <div v-for="(item, index) in followList" :key="index" 
                                class="flex py-2 flex-col items-center cursor-pointer hover:opacity-80 border border-gray-200 rounded-lg">
                                    <img :src="item.avatar" :alt="item.name" class="w-12 h-12 rounded-full mb-2 object-cover">
                                    <span class="px-2 text-sm text-gray-600 truncate w-full text-center">{{ item.userName }}</span>
                                </div>
                            </div>
                            <div v-else style="text-align: left;">暂无关注</div>
                        </div>
                    </div>
                    <!-- 社群 -->
                    <CommunityList />
                    <!-- 相关文章 -->
                    <section class="sidebar-section bg-white rounded-lg shadow-md overflow-hidden">
                        <h2
                            class="sidebar-title text-lg font-semibold p-4 pt-2 pb-0 bg-primary/10 text-gray-900 flex items-center gap-2">
                            <el-icon class="text-primary" color="#007bff">
                                <Star />
                            </el-icon>
                            热门文章
                        </h2>
                        <div v-for="item in hotArticles" :key="item.id"
                            @click="goDetails(item.id)"
                            class="hot-article cursor-pointer flex gap-4 px-4 py-2 border-b border-gray-200 transition-colors hover:bg-primary/5">
                            <div class="hot-article-image w-20 h-15 rounded overflow-hidden flex-shrink-0">
                                <img :src="item.coverImageUrl" :alt="item.title" class="w-full h-full object-cover">
                            </div>
                            <div class="hot-article-content flex-1 flex flex-col justify-between">
                                <h4 class="text-sm leading-relaxed font-medium line-clamp-2 mb-1">{{ item.title }}</h4>
                                <div class="hot-article-meta flex items-center gap-1 text-gray-500 text-xs">
                                    <el-icon>
                                        <View />
                                    </el-icon>
                                    <span>{{ item.viewCount }}</span>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- 贸行四海专栏 -->
                    <!-- <div class="bg-white rounded-lg shadow-md p-4">
                        <h3 class="text-lg font-semibold text-gray-800 mb-2">贸行四海专栏</h3>
                        <div class="space-y-4">
                            <div v-for="(column, index) in columns" :key="index" class="group cursor-pointer">
                                <h4 class="text-gray-800 group-hover:text-blue-600">{{ column.title }}</h4>
                                <p class="text-sm text-gray-500 mt-1">{{ column.author }}</p>
                            </div>
                        </div>
                    </div> -->

                    <!-- 热门报告 -->
                    <section class="sidebar-section bg-white rounded-lg shadow-md overflow-hidden" v-if="false">
                        <h2
                            class="sidebar-title text-lg font-semibold p-4 pt-2 pb-0 bg-primary/10 text-gray-900 flex items-center gap-2">
                            <el-icon class="text-primary" color="#007bff">
                                <Memo />
                            </el-icon>
                            热门报告
                            <span class="ml-auto text-sm text-gray-600 hover:text-blue-600 cursor-pointer" @click="goReportList">更多</span>
                        </h2>
                        <div class="space-y-4 px-4 py-2">
                            <div v-for="(report, index) in reports" :key="index" class="group cursor-pointer">
                               <h4 class="text-gray-800 group-hover:text-blue-600 line-clamp-1">
                                <span v-if="index === 0" style="color: #FD5B76; font-size: 20px;"> {{ index+1 }}.</span>
                                <span v-if="index === 1" style="color: #FFA342; font-size: 20px;"> {{ index+1 }}.</span>
                                <span v-if="index === 2" style="color: #818CF8; font-size: 20px;"> {{ index+1 }}.</span>
                                <span v-if="index == 3" style="color: gray; font-size: 16px;"> {{ index+1 }}.</span>
                                {{ report.title }}</h4>
                                <button class="text-sm text-gray-400 mt-1">2025-04-21</button>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { View, Clock, Star ,Memo} from '@element-plus/icons-vue';
import { getDictTypes } from "@/api/dict";
import { getNewsList, getNewsHot, getNewsAdList, getNewsTop } from "@/api/information";
import { useRouter } from "#vue-router";
import CommunityList from '@/components/communityList.vue'
import { getUserFollows } from "@/api/userAction";
import { HeartIcon } from '@/components/icons';

const currentSlide = ref(0)

const token = ref('');
const userStore = useUserStore();

onMounted(() => {
    token.value = userStore.token || localStorage.getItem('token')
})

const login = () =>{
    userStore.setShowLoginDialog(true)
}

const news_category = ref([]);
const getDictTypesFun = () => {
    getDictTypes({ types: 'news_category' }).then(res => {
        news_category.value = res.data.news_category;
    })
}

// 查询参数
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    category: ''
})

const total = ref(0)

const changeCategory = (category) => {
    queryParams.value.category = category;
    getNewsListFun();
}

const footerCarouselContainer = ref(null);
const footerCarouselWrapper = ref(null);
let currentIndex = 0;
let autoScrollInterval = null;

const displayAds = computed(() => {
    if (contentBottomAd.value.length <= 3) return contentBottomAd.value;
    
    // 在列表前后各添加广告项，实现无缝滚动
    // 前面添加最后两个广告项
    // 后面添加前两个广告项
    return [
        contentBottomAd.value[contentBottomAd.value.length - 2],
        contentBottomAd.value[contentBottomAd.value.length - 1],
        ...contentBottomAd.value,
        contentBottomAd.value[0],
        contentBottomAd.value[1]
    ];
});

const startAutoScroll = () => {
    if (contentBottomAd.value.length <= 3) return;
    
    // 先清除之前的定时器
    stopAutoScroll();
    
    // 初始位置设置为第二个广告（跳过前面添加的重复项）
    currentIndex = 2;
    if (footerCarouselWrapper.value) {
        footerCarouselWrapper.value.style.transform = `translateX(${-currentIndex * (100 / 3)}%)`;
    }
    
    autoScrollInterval = setInterval(() => {
        currentIndex = (currentIndex + 1) % (contentBottomAd.value.length + 4);
        const translateX = -currentIndex * (100 / 3);
        
        if (footerCarouselWrapper.value) {
            footerCarouselWrapper.value.style.transform = `translateX(${translateX}%)`;
            
            // 当滚动到倒数第二个时，立即跳转到第二个（视觉上无感知）
            if (currentIndex === contentBottomAd.value.length + 2) {
                setTimeout(() => {
                    currentIndex = 2;
                    footerCarouselWrapper.value.style.transition = 'none';
                    footerCarouselWrapper.value.style.transform = `translateX(${-currentIndex * (100 / 3)}%)`;
                    // 强制重排，确保样式更新
                    footerCarouselWrapper.value.offsetHeight;
                    footerCarouselWrapper.value.style.transition = 'transform 0.5s ease';
                }, 500);
            }
        }
    }, 3000);
}

const stopAutoScroll = () => {
    if (autoScrollInterval) {
        clearInterval(autoScrollInterval);
        autoScrollInterval = null;
    }
}

onMounted(() => {
    getDictTypesFun();
    getNewsListFun();
    getNewsHotFun();
    getNewsAdListFun();
    newsTopListFun();
    if(token.value){
        getUserFollowsFun();
    }
    
    // 确保DOM更新后再设置初始位置
    nextTick(() => {
        if (contentBottomAd.value.length > 3) {
            currentIndex = 2;
            if (footerCarouselWrapper.value) {
                footerCarouselWrapper.value.style.transition = 'none';
                footerCarouselWrapper.value.style.transform = `translateX(${-currentIndex * (100 / 3)}%)`;
                footerCarouselWrapper.value.offsetHeight;
                footerCarouselWrapper.value.style.transition = 'transform 0.5s ease';
            }
        }
    });
})

onUnmounted(() => {
    stopAutoScroll();
})

watch(
  () => userStore.token,
  (nv, ov) => {
    token.value = nv;
   if(nv){
    getUserFollowsFun();
   }
  },
  { deep: true, immediate: false }
);


const getUserFollowsFun = () => {
    getUserFollows({pageNum: 1, pageSize: 10,businessType: 'user'}).then(res => {
        console.log('获取用户关注成功', res);
        followList.value = res.data.list;
    })
}

const router = useRouter()

const goDetails = (id) => {
    const targetRoute = router.resolve({ path: '/information/informationDetails', query: { id } });
    window.open(targetRoute.href, '_blank');
}
// 轮播图数据
const carouselSlidesTop = ref([]);
const contentTopAd = ref({});
const contentBottomAd = ref([]);
const sidebarAd = ref([]);
const getNewsAdListFun = () => {
    getNewsAdList().then(res => {
        console.log(res);
        carouselSlidesTop.value = [];
        contentTopAd.value = {};
        contentBottomAd.value = [];
        sidebarAd.value = [];
        res.data.forEach(item => {
            if (item.adPosition === 'home_top') {
                carouselSlidesTop.value.push(item)
            }
            if (item.adPosition === 'content_top' && !contentTopAd.value.id) {
                contentTopAd.value = item;
            }
            if (item.adPosition === 'footer_carousel') {
                contentBottomAd.value.push(item);
            }
            if (item.adPosition === 'sidebar') {
                if (!sidebarAd.value.length < 3) {
                    sidebarAd.value.push(item);
                }
            }
        })
        // 确保DOM更新后再启动自动滚动
        nextTick(() => {
            startAutoScroll();
        });
    })
}


const newsList = ref([]);
const getNewsListFun = () => {
    getNewsList(queryParams.value).then(res => {
        total.value = res.data.total;
        newsList.value = res.data.list;
        // tags 根据逗号切割字符串，组合为数组
        newsList.value.forEach(item => {
            item.tagsBtn = item.tags?.split(',');
        })
    })
};

const newsTopList = ref([]);

const newsTopListFun = () => {
    getNewsTop(queryParams.value).then(res => {
        newsTopList.value = res.data;
    })
};


const hotArticles = ref([]);
const getNewsHotFun = () => {
    getNewsHot().then(res => {
        hotArticles.value = res.data;
    })
}

// 专栏数据
const columns = [
    {
        title: '2024年度出海企业必备合规指南',
        author: '贸行专家'
    },
    {
        title: '全球支付体系变革与企业应对策略',
        author: '贸行专家'
    }
]

// 报告数据
const reports = [
    {
        title: '《贸行四海 8大站点调研报告》PDF下载'
    },
    {
        title: '《贸行四海 8大站点调研报告》PDF下载'
    }, {
        title: '《贸行四海 8大站点调研报告》PDF下载'
    },
    {
        title: '《贸行四海 8大站点调研报告》PDF下载'
    }
]

const followList = ref([]);

const goAd = (item) => {
    window.open(item.jumpUrl, '_blank');
}

</script>

<style scoped>
.information-list {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.carousel-container {
    position: relative;
    width: 100%;
    height: 300px;
}

.carousel-img-box {
    height: 300px;
    position: relative;
    position: relative;
    display: flex;
    align-items: flex-start;
}

.filter-img-box {
    height: 100%;
    width: 40%;
    position: relative;

    .filter-img {
        height: 100%;
        width: 100%;
        position: absolute;
        z-index: 1;
        object-fit: cover;
    }

    .filter-text {
        height: 100%;
        width: 100%;
        position: absolute;
        z-index: 10;
    }

    .filter-bg {
        -webkit-backdrop-filter: blur(25px);
        backdrop-filter: blur(25px);
        background-position: 50%;
        background-repeat: no-repeat;
        background: hsla(0, 0%, 50%, .5);
        background-size: cover;
        filter: blur(15px);
        height: 100%;
        position: absolute;
        width: 100%;
        z-index: 2;
    }
}


.carousel-img-box .information-img {
    height: 100%;
    width: 60%
}

.carousel-img-box .title {
    padding: 5px;
    position: absolute;
    bottom: 50%;
    left: 40px;
    width: 100%;
    color: #fff;
    font-size: 32px;
}

.carousel-img-box .content {
    padding: 5px;
    text-align: right;
    position: absolute;
    bottom: 0;
    right: 0;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
}


.content-top-a {
    height: 80px;
    width: 100%;
    overflow: hidden;
    border-radius: 10px;
    cursor: pointer;
    position: relative;
}

.content-top-a img {
    height: 100%;
    width: 100%;
    object-fit: fill;
}

.description-box {
    white-space: normal !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    display: -webkit-box !important;
    -webkit-line-clamp: 2 !important;
    -webkit-box-orient: vertical !important;
}

.footer-carousel-box {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    position: relative;
    overflow: hidden;
}

.footer-carousel-container {
    width: 100%;
    overflow: hidden;
    padding-left: 10px;
}

.footer-carousel-wrapper {
    display: flex;
    transition: transform 0.5s ease;
    gap: 10px;
    width: 100%;
}

.footer-carousel {
    border-radius: 10px;
    width: calc(33.33% - 10px);
    height: 100px;
    position: relative;
    overflow: hidden;
    flex-shrink: 0;
}

.sidebar-a-box {
    position: relative;
}

.news-item-text {
    display: flex;
    flex-direction: column
}

.news-item-text .bottom-box {
    margin-top: auto;
}
</style>
